import React, { useState, useEffect } from 'react';
import { Table, Button, Modal, Form, Input, Select, Tag, message, Row, Col, Space, Switch, Spin, Card } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined, SearchOutlined, ReloadOutlined, LockOutlined } from '@ant-design/icons';
import './UserManagement.css';

const { Option } = Select;

const UserManagement = () => {
  const [loading, setLoading] = useState(false);
  const [userList, setUserList] = useState([]);
  const [total, setTotal] = useState(0);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [searchParams, setSearchParams] = useState({});
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isEditMode, setIsEditMode] = useState(false);
  const [currentUser, setCurrentUser] = useState(null);
  const [form] = Form.useForm();
  const [roles, setRoles] = useState([]);

  // 模拟用户数据 - 用于演示
  const mockUserList = [
    {
      id: '1',
      username: 'admin',
      nickname: '管理员',
      email: 'admin@example.com',
      phone: '13800138000',
      status: true,
      createTime: '2023-06-01 10:30:00',
      updateTime: '2023-06-15 15:20:00',
      roles: ['admin', 'user'],
      avatar: '/avatar/admin.png',
    },
    {
      id: '2',
      username: 'user1',
      nickname: '普通用户',
      email: 'user1@example.com',
      phone: '13800138001',
      status: true,
      createTime: '2023-06-02 11:15:00',
      updateTime: '2023-06-16 14:45:00',
      roles: ['user'],
      avatar: '/avatar/user1.png',
    },
    {
      id: '3',
      username: 'user2',
      nickname: '测试用户',
      email: 'user2@example.com',
      phone: '13800138002',
      status: false,
      createTime: '2023-06-03 09:20:00',
      updateTime: '2023-06-10 11:30:00',
      roles: ['user'],
      avatar: '/avatar/user2.png',
    },
    {
      id: '4',
      username: 'user3',
      nickname: '开发用户',
      email: 'user3@example.com',
      phone: '13800138003',
      status: true,
      createTime: '2023-06-04 14:05:00',
      updateTime: '2023-06-20 09:15:00',
      roles: ['developer', 'user'],
      avatar: '/avatar/user3.png',
    },
    {
      id: '5',
      username: 'user4',
      nickname: '运维用户',
      email: 'user4@example.com',
      phone: '13800138004',
      status: true,
      createTime: '2023-06-05 16:40:00',
      updateTime: '2023-06-25 16:00:00',
      roles: ['ops', 'user'],
      avatar: '/avatar/user4.png',
    },
  ];

  // 模拟角色数据
  const mockRoles = [
    { id: 'admin', name: '管理员', description: '系统管理员，拥有所有权限' },
    { id: 'developer', name: '开发人员', description: 'API开发人员，可管理API' },
    { id: 'ops', name: '运维人员', description: '系统运维人员，可监控系统' },
    { id: 'user', name: '普通用户', description: '普通用户，可使用API' },
  ];

  // 获取用户列表
  useEffect(() => {
    fetchUserList();
    fetchRoles();
  }, [currentPage, pageSize, searchParams]);

  const fetchUserList = async () => {
    try {
      setLoading(true);
      // 这里应该调用后端API获取用户列表
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 500));
      // 使用模拟数据
      setUserList(mockUserList);
      setTotal(mockUserList.length);
    } catch (error) {
      message.error('获取用户列表失败');
      console.error('获取用户列表失败:', error);
      // 出错时使用模拟数据
      setUserList(mockUserList);
      setTotal(mockUserList.length);
    } finally {
      setLoading(false);
    }
  };

  const fetchRoles = async () => {
    try {
      // 这里应该调用后端API获取角色列表
      // 使用模拟数据
      setRoles(mockRoles);
    } catch (error) {
      console.error('获取角色列表失败:', error);
      setRoles(mockRoles);
    }
  };

  // 刷新列表
  const handleRefresh = () => {
    setSearchParams({});
    setCurrentPage(1);
    setSelectedRowKeys([]);
    form.resetFields();
  };

  // 搜索
  const handleSearch = () => {
    const values = form.getFieldsValue();
    setSearchParams(values);
    setCurrentPage(1);
    setSelectedRowKeys([]);
  };

  // 清除搜索条件
  const handleClearSearch = () => {
    form.resetFields();
    setSearchParams({});
    setCurrentPage(1);
    setSelectedRowKeys([]);
  };

  // 打开添加用户模态框
  const showAddModal = () => {
    setIsEditMode(false);
    setCurrentUser(null);
    form.resetFields();
    setIsModalVisible(true);
  };

  // 打开编辑用户模态框
  const showEditModal = (record) => {
    setIsEditMode(true);
    setCurrentUser(record);
    // 转换角色数组为字符串数组
    const formValues = {
      ...record,
      roles: record.roles || [],
    };
    form.setFieldsValue(formValues);
    setIsModalVisible(true);
  };

  // 关闭模态框
  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  // 提交表单
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      setLoading(true);
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 800));
      
      if (isEditMode && currentUser) {
        // 更新用户
        message.success('更新成功');
      } else {
        // 创建用户
        message.success('创建成功');
      }
      setIsModalVisible(false);
      fetchUserList();
    } catch (error) {
      message.error('提交失败');
      console.error('提交错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 删除用户
  const handleDelete = async (id) => {
    try {
      Modal.confirm({
        title: '确定要删除这个用户吗？',
        content: '删除后将无法恢复，请谨慎操作。',
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          try {
            setLoading(true);
            // 模拟API调用延迟
            await new Promise(resolve => setTimeout(resolve, 500));
            message.success('删除成功');
            fetchUserList();
          } catch (error) {
            message.error('删除失败');
            console.error('删除错误:', error);
          } finally {
            setLoading(false);
          }
        },
      });
    } catch (error) {
      console.error('删除确认框错误:', error);
    }
  };

  // 批量删除用户
  const handleBatchDelete = async () => {
    try {
      if (selectedRowKeys.length === 0) {
        message.warning('请选择要删除的用户');
        return;
      }
      
      Modal.confirm({
        title: '确定要删除选中的用户吗？',
        content: `共 ${selectedRowKeys.length} 个用户将被删除，删除后将无法恢复，请谨慎操作。`,
        okText: '确定',
        okType: 'danger',
        cancelText: '取消',
        onOk: async () => {
          try {
            setLoading(true);
            // 模拟API调用延迟
            await new Promise(resolve => setTimeout(resolve, 500));
            message.success('批量删除成功');
            setSelectedRowKeys([]);
            fetchUserList();
          } catch (error) {
            message.error('批量删除失败');
            console.error('批量删除错误:', error);
          } finally {
            setLoading(false);
          }
        },
      });
    } catch (error) {
      console.error('批量删除确认框错误:', error);
    }
  };

  // 切换用户状态
  const handleToggleStatus = async (id, enabled) => {
    try {
      setLoading(true);
      // 模拟API调用延迟
      await new Promise(resolve => setTimeout(resolve, 300));
      message.success(enabled ? '启用成功' : '禁用成功');
      fetchUserList();
    } catch (error) {
      message.error('操作失败');
      console.error('切换状态错误:', error);
    } finally {
      setLoading(false);
    }
  };

  // 重置用户密码
  const handleResetPassword = (id, username) => {
    Modal.confirm({
      title: '重置密码',
      content: `确定要重置用户 ${username} 的密码吗？重置后密码将变为默认密码 123456。`,
      okText: '确定',
      okType: 'primary',
      cancelText: '取消',
      onOk: async () => {
        try {
          setLoading(true);
          // 模拟API调用延迟
          await new Promise(resolve => setTimeout(resolve, 300));
          message.success('密码重置成功');
        } catch (error) {
          message.error('密码重置失败');
          console.error('密码重置错误:', error);
        } finally {
          setLoading(false);
        }
      },
    });
  };

  // 表格列配置
  const columns = [
    {
      title: '用户名',
      dataIndex: 'username',
      key: 'username',
      ellipsis: true,
      sorter: (a, b) => a.username.localeCompare(b.username),
    },
    {
      title: '昵称',
      dataIndex: 'nickname',
      key: 'nickname',
      ellipsis: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      ellipsis: true,
    },
    {
      title: '手机号',
      dataIndex: 'phone',
      key: 'phone',
      ellipsis: true,
    },
    {
      title: '角色',
      dataIndex: 'roles',
      key: 'roles',
      render: (roles) => (
        <Space>
          {roles.map((role) => {
            let color = 'blue';
            if (role === 'admin') color = 'red';
            else if (role === 'user') color = 'green';
            return <Tag key={role} color={color}>{role}</Tag>;
          })}
        </Space>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status, record) => (
        <Switch
          checked={status}
          onChange={(checked) => handleToggleStatus(record.id, checked)}
          checkedChildren="启用"
          unCheckedChildren="禁用"
        />
      ),
      filters: [
        { text: '启用', value: true },
        { text: '禁用', value: false },
      ],
      onFilter: (value, record) => record.status === value,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      sorter: (a, b) => new Date(a.createTime) - new Date(b.createTime),
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      key: 'updateTime',
      sorter: (a, b) => new Date(a.updateTime) - new Date(b.updateTime),
    },
    {
      title: '操作',
      key: 'action',
      fixed: 'right',
      width: 180,
      render: (_, record) => (
        <Space size="middle">
          <Button
            type="text"
            icon={<EditOutlined />}
            onClick={() => showEditModal(record)}
            title="编辑"
          />
          <Button
            type="text"
            icon={<LockOutlined />}
            onClick={() => handleResetPassword(record.id, record.username)}
            title="重置密码"
          />
          <Button
            type="text"
            danger
            icon={<DeleteOutlined />}
            onClick={() => handleDelete(record.id)}
            title="删除"
            disabled={record.username === 'admin'} // 不允许删除管理员
          />
        </Space>
      ),
    },
  ];

  // 选择配置
  const rowSelection = {
    selectedRowKeys,
    onChange: (newSelectedRowKeys) => {
      setSelectedRowKeys(newSelectedRowKeys);
    },
    getCheckboxProps: (record) => ({
      disabled: record.username === 'admin', // 不允许选择管理员
    }),
  };

  return (
    <div className="user-management-container">
      <h2>用户管理</h2>
      
      {/* 搜索和操作栏 */}
      <Card className="search-card">
        <Row gutter={16}>
          <Col span={6}>
            <Form.Item name="username" label="用户名" className="search-item">
              <Input placeholder="请输入用户名" prefix={<SearchOutlined />} />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="nickname" label="昵称" className="search-item">
              <Input placeholder="请输入昵称" prefix={<SearchOutlined />} />
            </Form.Item>
          </Col>
          <Col span={6}>
            <Form.Item name="status" label="状态" className="search-item">
              <Select placeholder="请选择状态" allowClear>
                <Option value={true}>启用</Option>
                <Option value={false}>禁用</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={6} className="search-actions">
            <Space>
              <Button type="primary" icon={<SearchOutlined />} onClick={handleSearch}>
                搜索
              </Button>
              <Button onClick={handleClearSearch}>清除</Button>
              <Button onClick={handleRefresh} icon={<ReloadOutlined />}>
                刷新
              </Button>
            </Space>
          </Col>
        </Row>
      </Card>

      {/* 操作按钮 */}
      <div className="action-buttons">
        <Button type="primary" icon={<PlusOutlined />} onClick={showAddModal}>
          添加用户
        </Button>
        <Button danger onClick={handleBatchDelete} disabled={selectedRowKeys.length === 0}>
          批量删除
        </Button>
        <span className="selected-count">已选择 {selectedRowKeys.length} 项</span>
      </div>

      {/* 用户列表表格 */}
      <Spin spinning={loading} tip="加载中...">
        <Table
          rowSelection={rowSelection}
          columns={columns}
          dataSource={userList}
          rowKey="id"
          pagination={{
            current: currentPage,
            pageSize,
            total,
            onChange: (page, pageSize) => {
              setCurrentPage(page);
              setPageSize(pageSize);
            },
            showSizeChanger: true,
            showTotal: (total) => `共 ${total} 条数据`,
            pageSizeOptions: ['10', '20', '50', '100'],
          }}
          scroll={{ x: 1200 }}
          className="user-table"
        />
      </Spin>

      {/* 添加/编辑用户模态框 */}
      <Modal
        title={isEditMode ? '编辑用户' : '添加用户'}
        open={isModalVisible}
        onCancel={handleCancel}
        footer={null}
        width={700}
      >
        <Form form={form} layout="vertical" onFinish={handleSubmit}>
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="username"
                label="用户名"
                rules={[
                  { required: true, message: '请输入用户名' },
                  { pattern: /^[a-zA-Z0-9_]{3,20}$/, message: '用户名只能包含字母、数字和下划线，长度为3-20位' },
                ]}
                hasFeedback
              >
                <Input placeholder="请输入用户名" disabled={isEditMode} />
              </Form.Item>
            </Col>
            <Col span={12}>
              {!isEditMode && (
                <Form.Item
                  name="password"
                  label="密码"
                  rules={[
                    { required: true, message: '请输入密码' },
                    { pattern: /^[a-zA-Z0-9_]{6,20}$/, message: '密码只能包含字母、数字和下划线，长度为6-20位' },
                  ]}
                  hasFeedback
                >
                  <Input.Password placeholder="请输入密码" />
                </Form.Item>
              )}
              {isEditMode && (
                <Form.Item
                  name="nickname"
                  label="昵称"
                  rules={[{ required: true, message: '请输入昵称' }]}
                >
                  <Input placeholder="请输入昵称" />
                </Form.Item>
              )}
            </Col>
          </Row>
          
          {!isEditMode && (
            <Row gutter={16}>
              <Col span={12}>
                <Form.Item
                  name="nickname"
                  label="昵称"
                  rules={[{ required: true, message: '请输入昵称' }]}
                >
                  <Input placeholder="请输入昵称" />
                </Form.Item>
              </Col>
            </Row>
          )}
          
          <Row gutter={16}>
            <Col span={12}>
              <Form.Item
                name="email"
                label="邮箱"
                rules={[
                  { required: true, message: '请输入邮箱' },
                  { type: 'email', message: '请输入有效的邮箱地址' },
                ]}
                hasFeedback
              >
                <Input placeholder="请输入邮箱" />
              </Form.Item>
            </Col>
            <Col span={12}>
              <Form.Item
                name="phone"
                label="手机号"
                rules={[
                  { required: true, message: '请输入手机号' },
                  { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号' },
                ]}
                hasFeedback
              >
                <Input placeholder="请输入手机号" />
              </Form.Item>
            </Col>
          </Row>
          
          <Form.Item
            name="roles"
            label="角色"
            rules={[{ required: true, message: '请至少选择一个角色' }]}
          >
            <Select mode="multiple" placeholder="请选择角色">
              {roles.map((role) => (
                <Option key={role.id} value={role.id}>
                  {role.name} ({role.description})
                </Option>
              ))}
            </Select>
          </Form.Item>
          
          <Form.Item name="status" label="状态" valuePropName="checked">
            <Switch checkedChildren="启用" unCheckedChildren="禁用" defaultChecked />
          </Form.Item>
          
          <div className="modal-actions">
            <Button onClick={handleCancel} style={{ marginRight: 8 }}>
              取消
            </Button>
            <Button type="primary" htmlType="submit" loading={loading}>
              {isEditMode ? '更新' : '创建'}
            </Button>
          </div>
        </Form>
      </Modal>
    </div>
  );
};

export default UserManagement;